// stores/permission.js
import { defineStore } from 'pinia'
import { authRoutes } from '@/router/routes'

export const usePermissionStore = defineStore('permission', {
  state: () => ({
    routes: [],
    hasGenerated: false // 保持这个状态名称
  }),

  actions: {
    // 确保generateRoutes正确设置状态
    // 在generateRoutes方法中添加：
    async generateRoutes(roles) {
      try {
        if (this.hasGenerated) return
        
        const userRoles = roles // 从参数获取用户角色
        const filterRoutes = (routes) => 
          routes.filter(route => {
            // 验证路由权限
            const requiredRoles = route.meta?.roles || []
            const hasPermission = requiredRoles.length === 0 || 
                            requiredRoles.some(r => userRoles.includes(r))
            
            // 验证子路由权限
            const hasValidChildren = route.children?.some(child => 
              !child.meta?.hidden && (child.component || child.children?.length)
            )
            
            return !route.meta?.hidden && hasPermission && 
                  (!!route.component || hasValidChildren)
          }).map(route => ({
            ...route,
            children: route.children ? filterRoutes(route.children) : []
          }))
        
        this.routes = filterRoutes(authRoutes)
        this.hasGenerated = true
      } catch (error) {
        console.error('路由生成失败:', error)
      }
    }

  }
})
